<?php

namespace zhtfrontend\modules\touch\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\components\helpers\Util;
use common\models\datas\Admissionfee;
use common\models\datas\Cate;
use common\models\datas\Classhourfee;
use common\models\datas\Customer;
use common\models\datas\Student;
use zhtfrontend\components\services\classmanager\Operclassmanager;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\Classroom;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\LessonStudent;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\Teacher;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\helpers\Html;
use common\models\datas\CardAttr;
use yii\data\Pagination;
use yii\widgets\LinkPager;
use yii\helpers\HtmlPurifier;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageTeacher;

class DefaultController extends Controller
{
    public $touch=true;
    public function actionIndex()
    {
        $mids = Fun::getMechanicIds();
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'attr') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $card_id = \Yii::$app->request->post('card_id');

            $customer = Customer::find()->where(['card_id' => $card_id])->one();
            $ajax_object = new AjaxObject();
            if ($card_id==2603021337){
                $print_url=Fun::url(['/touch/default/print','ids'=>'','card_id'=>'']);
                $print_data=[
                    'id'=>'测试卡号',
                    'print_url'=>$print_url,
                    'count'=>2603021337,
                ];
                $ajax_object->data = $print_data;
                $str='<h2>测试数据打印</h2>
                      <p>测试数据打印</p>
                      <button class="cj-lock-confirm" data-url1="' . Fun::url(["touch/default/index"]) . '"  data-id="' . 2603021337 . '" data-ids="' . 2603021337 . '"></button>';
                $ajax_object->content = $str;
                return $ajax_object;
            }
            if ($customer !== null && $customer->card_id !== null) {
                //获取持有当前卡号的用户的id
                $user_id = $customer->id;
                //获取当前用户的孩子的信息
                $student = Student::find()->where(['customer_id'=>$user_id])->one();
                //在class_student表查找改学生的已开班的课程 数组
                $class_student_lists =ClassStudent::find()->where(['student_id' => $student->id, 'status' => [1,5]])->all();
                //机构登陆只查询自己的课程
//                if(!empty($mids)){
//                    $class_student = ClassManage::find()->select('class_id')->where(['class_id'=>$class_student,'mechanic_id'=>$mids])->column();
//                }
                $id = [];
                $ids = [];
                $str = '';
                $lesson_ids = [];
                $class_student_ids = [];
                $class_manage_ids = [];
                if (!empty($class_student_lists)) {
                    foreach ($class_student_lists as $classstudent){
                        $class_manage_ids[] = $classstudent->class_manage_id;
                        $class_student_ids[] = $classstudent->id;
                        if($classstudent->is_frequency == 0){
                            if(time() <= $classstudent->end_time){
                                $classattr = ClassManageAttribute::find()->where(['class_id'=>$classstudent->class_manage_id])->one();
                                $newClass = ClassManageAttribute::find()->where(['course_id'=>$classattr->course_id])->andWhere(['<>','class_id',$classstudent->class_manage_id])->all();
                                if($newClass != null){
                                    foreach ($newClass as $newc){
                                        $class_manage_ids[] = $newc->class_id;
                                    }

                                }
                            }
                        }
                    }

                    $check_status = 1;//默认已打卡
                    //查询class_manage表 查询今天 对应时间的课程
                    $time_start = strtotime(date('Y-m-d'));
                    $time_end = $time_start + 86400;
                    //根据开始 结束时间条件 查找
                    $time_1 = date('Hi',time()+2*60*60);
                    $time_2 = date('Hi',time()-2*60*60);
                    //查找今天的课程可能一天上两节课数组(classlesson表里面class_id等于之前class_manage_id)
                    //打卡的时间限制是可以在上课前的两个小时打卡(上课后的两个小时)，可以在课程结束前的两个小时打卡(课程结束后的两个小时内)
                    $class_lessons = ClassLesson::find()->where(['class_id'=>$class_manage_ids])
                        ->andwhere(['>=','class_date',$time_start])
                        ->andwhere(['<=','class_date',$time_end])
                        ->orderBy('class_date ASC')
                        ->all();
                    if($class_lessons != null) {
                        $str .= '<img src="/images/images/sh.gif" width="25%"/>
                                        <h2>欢迎<span>' . Html::encode($student->name) . '</span>小朋友来到豆苗朵</h2>
                                        <p >你在1小时内的课程如下：</p>';
                        $str .='<table border="0" cellspacing="0" cellpadding="0" class="cj-class-content">
                                        <thead>
                                            <tr>
                                                <th>上课老师</th>
                                                <th>时间</th>
                                                <th>状态</th>
                                                <th>课程名称</th>
                                                <th class="last">上课地点</th>
                                            </tr>
                                        </thead>';
                        foreach ($class_lessons as $val) {
                            $lesson_ids[]=$val->lesson_id;
                            $check_start = $val->class_date - (2 * 60 * 60);//课程开始前的2个小时
                            $check_end = $time_start + (substr($val->end_time, -2) * 60) + (floor($val->end_time/100) * 60 * 60)+(2*60*60);//课程结束后的一个半小时
                            //找到符合条件的class_lesson
                            $time = time();
                            $class_state = '未打卡';
                            $check_status = 0;
                            $is_exist = false;
                            if ($check_start <= $time && $time <= $check_end) {

                                //$class_student_ids = ClassStudent::find()->select('id')->where(['class_manage_id'=>$val->class_id,'student_id'=>$student->id])->column();
                                $student_check = StudentCheck::find()->where(['class_lesson_id'=>$val->lesson_id,'student_id'=>$student->id])->one();
                                $lesson_student = LessonStudent::find()->where(['lesson_id'=>$val->lesson_id,'student_id'=>$student->id])->one();
                                if($student_check != null && $lesson_student != null){
                                    $is_exist = true;
                                    if ($student_check->status != 0 && $lesson_student->status != 0) {
                                        $class_state = '已打卡';
                                        $check_status = 1;
                                        $ids[] = $val->lesson_id;
                                    } else {
                                        $class_state = '未打卡';
                                        $id[] = $val->lesson_id;
                                        $ids[] = $val->lesson_id;
                                        $check_status = 0;
                                    }

                                } else {
                                    $row = ClassStudent::find()->where(['student_id'=>$student->id,'status'=>1,'is_frequency'=>0])->one();
                                    if($row != null) {
                                        $for =ClassManageAttribute::find()->where(['class_id'=>$val->class_id])->one();
                                        $frequency =ClassManageAttribute::find()->where(['class_id'=>$row->class_manage_id])->one();
                                        if($for->course_id == $frequency->course_id) {
                                            $is_exist = true;
                                            $class_state = '未打卡';
                                            $id[] = $val->lesson_id;
                                            $ids[] = $val->lesson_id;
                                            $check_status = 0;
                                        }
                                    }
                                }

                                //查询class_manage表数据
                                if($is_exist) {
                                    $nomal_start = isset($val->start_time) ? Util::getTime($val->start_time) : '';
                                    $nomal_end = isset($val->end_time) ? Util::getTime($val->end_time) : '';
                                    $class_manage = ClassManage::findOne(['class_id' => $val->class_id]);
                                    if ($class_manage->is_old == 0) {
                                        //若是新班 获取课程的相关的信息
                                        $classAttr = ClassManageAttribute::find()->where(['class_id' => $val->class_id])->one();
                                        $teacherList = ClassManageTeacher::find()->select('teacher_name')->where(['class_id' => $val->class_id])->column();
                                        $srt = '';
                                        if (!empty($teacherList)) {
                                            $srt = implode(',', $teacherList);
                                        }
                                        $str .= '
                                        <tbody>
                                            <tr>
                                                <td>' . Html::encode($srt) . '</td>
                                                <td>' . Html::encode($nomal_start) . '-' . Html::encode($nomal_end) . '</td>
                                                <td>' . Html::encode($class_state) . '</td>
                                                <td width="215px">' . Html::encode(isset($val->title) ? $val->title : '') . '</td>
                                                <td>' . Html::encode(isset($classAttr->classroom->name) ? $classAttr->classroom->name : '') . '</td>
                                            </tr>
                                        </tbody>';
                                    } else {
                                        //若为老生 查找arrangement表
                                        $course_infomation = Arrangement::findone(['id' => $val->classManage->associate_id]);
                                        $str .= '
                                        <tbody>
                                            <tr>
                                                <td>' . Html::encode(isset($course_infomation->teacher->name) ? $course_infomation->teacher->name : '') . '</td>
                                                <td>' . Html::encode($nomal_start) . '-' . Html::encode($nomal_end) . '</td>
                                                <td>' . Html::encode($class_state) . '</td>
                                                <td width="215px">' . Html::encode(isset($val->title) ? $val->title : '') . '</td>
                                                <td>' . Html::encode(isset($course_infomation->classroom->name) ? $course_infomation->classroom->name : '') . '</td>
                                            </tr>
                                        </tbody>';
                                    }
                                }
                            }
                        }
                        $str .='</table>';
                        $lesson_idstr=implode(',',$id);
                        $print_url=Fun::url(['/touch/default/print','ids'=>$lesson_idstr,'card_id'=>$student->id]);
                        $print_data=[
                            'id'=>array_values($id),
                            'print_url'=>$print_url,
                            'count'=>count($id),
                            'class_students'=>array_unique($class_student_ids)
                        ];
                        if(count($ids) > 0){
                            if(count($id) > 0){
                                $ajax_object->data=$print_data;
                                $str .= ' <button class="cj-lock-confirm" id="ticket-print-touch" data-url1="' . Fun::url(["touch/default/index"]) . '"  data-id="' . serialize($id) . '" data-ids="' . ($student->id) . '" data-class_student="' .implode(',',$class_student_ids). '"></button>';
                            }else{
                                $ajax_object->data = 0;
                                $str .= ' <button class="cj-lock-confirm cj-lock-disable" data-url1="' . Fun::url(["touch/default/index"]) . '"  data-id="' . serialize($id) . '" data-ids="' . ($student->id) . '"></button>';
                            }
                            $ajax_object->content = $str;
                        } else {
                            $str = '<img src="/images/images/clock-sun.png" class="cj-clock-sun">
                            <img src="/images/images/sh.gif" width="25%"/>
                            <h2>欢迎<span>'. Html::encode($student->name) . '</span>小朋友来到豆苗朵</h2>
                             <p>你在1小时内的课程如下：</p>
                             <p class="cj-clock-red">现在暂时没有您需要上的课程，在广场随便溜达溜达吧！</p>
                             <button class="cj-lock-confirm cj-lock-disable"></button>
                             ';
                            $ajax_object->data = '您没课';
                            $ajax_object->content = $str;
                        }
                    }else{
                        $str = '<img src="/images/images/clock-sun.png" class="cj-clock-sun">
                            <img src="/images/images/sh.gif" width="25%"/>
                            <h2>欢迎<span>'. Html::encode($student->name) . '</span>小朋友来到豆苗朵</h2>
                             <p>你在1小时内的课程如下：</p>
                             <p class="cj-clock-red">现在暂时没有您需要上的课程，在广场随便溜达溜达吧！</p>
                             <button class="cj-lock-confirm cj-lock-disable"></button>
                             ';
                        $ajax_object->data = '您没课';
                        $ajax_object->content = $str;
                    }
                }else{
                    $str = '<img src="/images/images/clock-sun.png" class="cj-clock-sun">
                            <img src="/images/images/sh.gif" width="25%"/>
                            <h2>欢迎<span>'. Html::encode($student->name) . '</span>小朋友来到豆苗朵</h2>
                             <p>你在1小时内的课程如下：</p>
                             <p class="cj-clock-red">现在暂时没有您需要上的课程，在广场随便溜达溜达吧！</p>
                             <button class="cj-lock-confirm cj-lock-disable"></button>
                             ';
                    $ajax_object->data = '您没课';
                    $ajax_object->content = $str;
                }
            }else {
                $str='
                      <img src="/images/images/clock-sun.png" class="cj-clock-sun">
                      <img src="/images/images/clcok-question.gif" width="35%">
                      <p>很抱歉，你的卡号不存在</p>
                      <p class="p-small">请确认后重新打卡</p>
                      <button class="cj-lock-disableno" ></button>';
                $ajax_object->data = '卡号不存在';
                $ajax_object->content = $str;
            }
            return $ajax_object;
        }
        //下面是按钮点击部分的代码
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'status') {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $lesson_id = \Yii::$app->request->post('id');
            $student_id = \Yii::$app->request->post('ids');
            $class_students = \Yii::$app->request->post('class_students');
            if($student_id=="2603021337"){
                return 3;
            }
            $lesson_id = unserialize($lesson_id);
            $class_students = explode(',',$class_students);
            if ($lesson_id == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
            }
//            if($class_students == null){
//                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
//            }

            foreach($lesson_id as $id) {
                //根据传来的lesson_id 查找student_check lesson_student表
                $class_lesson = ClassLesson::findone(['lesson_id' => $id]);
                $student_check = StudentCheck::findone(['class_lesson_id' => $id,'student_id'=>$student_id]);
                $lesson_student = LessonStudent::findOne(['lesson_id' => $id,'student_id'=>$student_id]);
                $newclassAttr = ClassManageAttribute::find()->where(['class_id'=>$class_lesson->class_id])->one();
                if($class_lesson->status == 0){
                    $class_lesson->status =1;
                    $class_lesson->save(false);
                }
                if (($student_check != null && $student_check->status != 0) && ($lesson_student != null && $lesson_student->status != 0)) {
                    return 2;
                } else {
                    if($student_check != null){
                        $row_class_student_id = $student_check->class_student_id;
                        $student_check->status = 1;
                        $student_check->created_at = time();
                        $student_check->save(false);
                        //修改lesson_student表
                        $lesson_student->status = 1;
                        $lesson_student->check_time= time();
                        $lesson_student->save(false);
                        Operclassmanager::AddCheckCount($student_check->id);
                    }else{
                        foreach ($class_students as $class_student_id){
                            $row = ClassStudent::findOne($class_student_id);
                            if($row->is_frequency == 0){
                                $frequencyClass = ClassManageAttribute::find()->where(['class_id'=>$row->class_manage_id])->one();
                                if($frequencyClass->course_id == $newclassAttr->course_id){
                                    $row_class_student_id = $row->id;
                                    $newstudent_check = new StudentCheck();
                                    $newstudent_check->class_student_id = $row->id;
                                    $newstudent_check->order_sales_id = $row->order_sales_id;
                                    $newstudent_check->student_id = $row->student_id;
                                    $newstudent_check->status = 1;
                                    $newstudent_check->created_at = time();
                                    $newstudent_check->class_lesson_id = $class_lesson->lesson_id;
                                    $newstudent_check->save(false);

                                    $newLessonStudent = new LessonStudent();
                                    $newLessonStudent->lesson_id = $class_lesson->lesson_id;
                                    $newLessonStudent->check_time = time();
                                    $newLessonStudent->status = 1;
                                    $newLessonStudent->student_id = $row->student_id;
                                    $newLessonStudent->save(false);

                                    Operclassmanager::AddCheckCount($newstudent_check->id);
                                }
                            }
                        }
                    }
                    //如果是打卡超过本课程的3分之一的话，就往表里面插入一条数据
//                    $class_manage = ClassManage::findone(['class_id' => $class_lesson->class_id]);
//                    if ($class_manage->is_old == 0) {
//                        //查询总上课数
//                        $class_count = ClassLesson::find()->where(['class_id' => $class_lesson->class_id])->count();
//                        $count = $class_lesson->lesson;
//                        $Proportion_number = $class_count / 3;
//                        $Mechanic = Mechanic::findOne($class_manage->mechanic_id);
//                        if($Mechanic->enrollment_ratio > 0){
//                            $Proportion_number = ceil($class_count*($Mechanic->enrollment_ratio/100));
//                        }
//                        if ($Proportion_number < $count) {
//                            $classGoods = ClassManageGoods::find()->where(['class_id'=>$class_lesson->class_id])->orderBy('goods_id DESC')->limit(1)->one();
//                            $adminssionfee = Admissionfee::find()->where(['student_id' => $student_id, 'goods_id' => $classGoods->goods_id,'class_student_id'=>$row_class_student_id])->one();
//                            $student=Student::findOne($student_id);
//                            $customer = Customer::findOne($student->customer_id);
//                            if ($adminssionfee == null) {
//                                $admission = new Admissionfee();
//                                $admission->customer_id = $customer->id;
//                                $admission->student_id = $student_id;
//                                $admission->mechanic_id = $class_manage->mechanic_id;
//                                $admission->class_id = $class_manage->class_id;
//                                $admission->class_student_id = $row_class_student_id;
//                                $admission->site_id = Fun::getSiteId();
//                                $admission->status = '0';
//                                $admission->created_at = time();
//
//
//                                $goods = Goods::findone($classGoods->goods_id);
//                               // $classroom = GoodsAttr::find()->select('attribute_id,value')->where(['goods_id' => $class_manage->associate_id, 'obj_type' => 'classroom_name'])->one();
//
//                               // $teacher = GoodsAttr::find()->select('attribute_id,value')->where(['goods_id' => $class_manage->associate_id, 'obj_type' => 'teacher'])->one();
//                                $teacher = ClassManageTeacher::find()->where(['class_id'=>$class_lesson->class_id])->one();
//                                $salesman = CardAttr::find()->where(['customer_id'=>$customer->id])->one();
//
//                                $student_age = date('Y') - $student->age;
//                                $admission->goods_id = $classGoods->goods_id;
//                                $admission->mechanic_name = $Mechanic->name;
//                                $admission->goods_name = $goods->name;
//                                $admission->admissionfee = $goods->admission_fee;
//                                $admission->classroom_id = $newclassAttr->room_id;
//                                $admission->classroom_name = $newclassAttr->classroom_name;
//                                $admission->teacher_id = $teacher->teacher_id;
//                                $admission->teacher_name = $teacher->teacher_name;
//                                $admission->class_date = $class_lesson->class_date;
//                                $admission->class_day = date('w', $class_lesson->class_date);
//                                $admission->class_start = $class_lesson->start_time;
//                                $admission->class_end = $class_lesson->end_time;
//                                $admission->customer_name = $customer->name;
//                                $admission->student_name = $student->name;
//
//                                $admission->cate_id = !empty($goods)?$goods->cat_id:0;
//                                $admission->mechanic_area = !empty($mechanic)?$mechanic->region:'';
//                                $admission->salesman_id = !empty($salesman)?$salesman->salesman_id:0;
//                                $admission->student_age = !empty($student_age)?$student_age:0;
//                                $admission->save(false);
//                            }
//                        }
//                    }
                }
            }
            return 1;
        }
        return $this->render('index');
    }

    public function actionPrint()
    {
        $str = '豆苗朵广场';
        if(\Yii::$app->request->get('ids') != null&&\Yii::$app->request->get('card_id') != null){
            $student_id=\Yii::$app->request->get('card_id');
            $student=Student::find()->where(['id'=>$student_id])->one();
            $ids=\Yii::$app->request->get('ids');
            $ids_array=explode(',',$ids);
            foreach ( $ids_array as $key=>$val){
                //查找lesson_id关联的class_id
                $class_id=ClassLesson::find()->where(['lesson_id'=>$val])->one();
                //判断是技教学还是艺教学，去不同的表里查,技教学是good_attr表，艺教学是art_teaching
                $goods=[];
                if($class_id->product_id==0){//等于0的话就是技教学
//                    $associate_id=ClassManage::find()->where(['class_id'=>$class_id->class_id])->one();
                    //去good_attr表里面查相关的信息
                    $classAttr = ClassManageAttribute::find()->where(['class_id'=>$class_id->class_id])->one();
//                    $goods=GoodsAttr::find()->where(['goods_id'=>$associate_id->associate_id])->indexBy('obj_type')->asArray()->all();
                    $teacherList = ClassManageTeacher::find()->select('teacher_name')->where(['class_id'=>$class_id->class_id])->column();
                    $teacherStr = '';
                    if(!empty($teacherList)){
                        $teacherStr = implode(',',$teacherList);
                    }
                    $str.="<div class=".'cj-xp'."><h2>" . Html::encode(Fun::getSiteName()) . "</h2>";
                    $str .= "<p>票据编号:<span>" . Html::encode(\Yii::$app->formatter->asTimestamp(time())) . "</span></p><p>开票时间：<span>" . date('Y-m-d') . "</span></p>";
                    $str .= "<p>姓名：<span>" . Html::encode(isset($student->name)?$student->name:'') . "</span></p><p>课程:<span>" . Html::encode($class_id->title) . "</span></p>";
                    $str .= "<p>老师:<span>" . Html::encode($teacherStr) . "</span></p><p>上课时间：<span>" . Html::encode(isset($class_id->start_time)?Util::getTime($class_id->start_time):'') . '-' . Html::encode(isset($class_id->end_time)?Util::getTime($class_id->end_time):'') . "</span></p>";
                    $str .= "<p>教室：<span>" . Html::encode($classAttr->classroom_name) . "</span></p><p>注：凭小票进入教学区</p></div>";
                }else{//下面是艺教学的表，需要利用product_id字段到arrangement表
                    $arrange_id=Arrangement::find()->where(['id'=>$class_id->product_id])->one();
                    $course=Course::find()->where(['id'=>$arrange_id->course_id])->one();
                    $teacher=Teacher::find()->where(['id'=>$arrange_id->teacher_id])->one();
                    $classroom=Classroom::find()->where(['id'=>$arrange_id->classroom_id])->one();
                    $str.="<div class=".'cj-xp'."><h2>" . Html::encode(Fun::getSiteName()) . "</h2>";
                    $str .= "<p>票据编号:<span>" . Html::encode(\Yii::$app->formatter->asTimestamp(time())) . "</span></p><p>开票时间：<span>" . date('Y-m-d') . "</span></p>";
                    $str .= "<p>姓名：<span>" .  Html::encode(isset($student->name)?$student->name:'') . "</span></p><p>课程:<span>" . Html::encode(isset($course->name)?$course->name:'') . "</span></p>";
                    $str .= "<p>老师:<span>" . Html::encode(isset($teacher->name)?$teacher->name:'') . "</span></p><p>上课时间：<span>" . Html::encode(isset($class_id->start_time)?date('Y-m-d',$class_id->start_time):'') . '-' . Html::encode(isset($class_id->end_time)?date('Y-m-d',$class_id->end_time):'') . "</span></p>";
                    $str .= "<p>教室：<span>" . Html::encode(isset($classroom->name)?$classroom->name:'') . "</span></p><p>注：凭小票进入教学区</p></div>";
                }
            }
        }else{
            $str = '测试数据测试数据';
        }
        return $this->render('print', ['data' => $str]);
    }

    public function acrionTest(){

    }

    public function beforeAction($action)
    {
        \Yii::$app->view->title = Fun::getSiteName();
        return parent::beforeAction($action);
    }
    public function datetime($date){
        if($date=='星期一'){
            $date=1;
        }elseif($date=='星期二'){
            $date=2;
        }elseif($date=='星期三'){
            $date=3;
        }elseif($date=='星期四'){
            $date=4;
        }elseif($date=='星期五'){
            $date=5;
        }elseif($date=='星期六'){
            $date=6;
        }else{
            $date=7;
        }
        return $date;
    }
}
